import { Fragment, useEffect } from 'react';
import style from './index.less';
import { Popover, Spin, Input, Button, Tooltip } from 'antd';
import { useSetState } from 'ahooks';
import { connect } from 'dva';
import { history } from 'umi';
import classnames from 'classnames';

import { TRDefault, TRMessage } from '@/components';
import { default as TREditAppLogoModal } from '@/components/EditAppLogo';
import { RetweetOutlined, SearchOutlined, RightOutlined } from '@/utils/antdIcons';
import { queryMenuPowerNew, visitRecord } from '@/services/power';
import { HttpCode } from '@/utils/contacts';
import { jumpEdoc, queryFanRuanSsoToken } from '@/services/login';
import { getFanRuanSsoToken } from '@/utils/authority';
import { findNodeByCodeBFS } from '@/utils/utils';

const AppBasicPopover = (props) => {
  const [state, setState] = useSetState({
    commonList: [],
    seachMenuList: [],
    isRequest: false,
    searchValue: '',
    visible: false,
    inputVisible: false,
    appContentLoading: false,
    // appList: [],
    appList: Object.values(props.menuObj).reduce((p, c) => [...p, c], []),
  });

  useEffect(() => {
    setState({
      appList: Object.values(props.menuObj).reduce((p, c) => [...p, c], []),
    });
  }, [props.menuObj]);

  /**
   * 记录打开的应用
   * @param {*} data
   */
  const _visitRecord = (data) => {
    visitRecord(data);
  };

  // 处理输入框查询 下拉展示model
  const handleIpuntVisibleChange = (inputVisible) => {
    setState({ inputVisible });
  };

  // 高级查询跳转应用
  const jumpApp = (menuItem) => {
    const { dispatch } = props;
    const data = {
      customApplicationId: menuItem?.customApplicationId || '',
    };
    _visitRecord(data);
    if (dispatch) {
      dispatch({
        type: 'user/onMeunList',
        payload: {
          id: menuItem?.customApplicationId || '',
          appName: menuItem?.customApplicationName || '',
        },
      });
    }
    setState({
      visible: false,
    });
  };

  const handlerList = (array, pIndex = 0, pName = '') => {
    return array.reduce((pre, cur) => {
      const parentName = pIndex == 1 ? cur.name : pName;
      if (cur.children?.length) {
        const list = handlerList(cur.children, pIndex + 1, parentName);
        if (pIndex == 0) {
          cur.children = list;
        } else {
          return pre.concat(list);
        }
      }
      if (pIndex == 0) {
        cur.name = cur.customApplicationName;
      } else {
        cur.menuName = pName + '-' + cur.name;
      }
      pre.push(cur);
      return pre;
    }, []);
  };

  // 输入框查询操作
  const hanldeInput = async () => {
    const { searchValue } = state;
    if (!searchValue) return;
    const params = {
      searchName: searchValue,
    };
    const res = await queryMenuPowerNew(params);
    if (res?.statusCode == HttpCode.SUCCESS) {
      const commonList = handlerList(res?.data || []) || [];
      setState({
        commonList: commonList,
        inputVisible: true,
        seachMenuList: commonList?.[0] || {},
      });
      if (commonList.length) {
        const contentRightNode = document.querySelectorAll(
          '.BasicLayout-ProLayout-Popover-inputSeach .contentRight .nameItem',
        );
        if (contentRightNode?.length) {
          for (let i = 0; i < contentRightNode.length; i++) {
            if (i === 0) {
              contentRightNode[i].classList.add('nameItem-action');
            } else {
              contentRightNode[i].classList.remove('nameItem-action');
            }
          }
        }
      }
    } else {
      setState({
        commonList: [],
        inputVisible: true,
        seachMenuList: [],
      });
    }
  };
  // 跳转输入框查询  跳转
  const jumpSeachPath = async (menuItem) => {
    const findNode = findNodeByCodeBFS(menuItem.menuCode);
    if (findNode?.perms === '1') {
      window.open(`${window.location.origin}/#/saas${menuItem?.path}`);
      return;
    }
    const { seachMenuList } = state;
    const { dispatch, appName, appLogo } = props;
    if (menuItem.url === 'logoWEB') {
      setState({ inputVisible: false, visible: false });
      TREditAppLogoModal.show({ appLogo });
      return;
    }

    if (menuItem.path === '/smart/zhiNengBaoBiao') {
      let ssoToken = getFanRuanSsoToken();
      const response = await queryFanRuanSsoToken();
      if (response.statusCode === HttpCode.SUCCESS && response.encrypt) {
        ssoToken = response.ssoToken;
      } else {
        TRMessage.error(response.message || '请求失败，请稍后再试');
        return;
      }
      return window.open('https://bi.gw-ams.com/webroot/decision?ssoToken=' + ssoToken);
    }

    if (menuItem.path === '/edocJump') {
      const res = await jumpEdoc();
      if (res?.statusCode === HttpCode.SUCCESS) {
        return window.open(res.data);
      } else {
        TRMessage.error(res.message || '请求失败，请稍后再试');
        return;
      }
    }

    // 如果是当前页面
    if (menuItem.customApplicationName === appName && !menuItem.isEam) {
      history.push(`/${menuItem.url}`);
    } else {
      dispatch &&
        dispatch({
          type: 'user/onMeunList',
          payload: {
            id: seachMenuList.customApplicationId,
            appName: seachMenuList.name,
            menuCode: menuItem.menuCode,
            url: menuItem.url,
          },
        });
    }
    const data = {
      customApplicationId: seachMenuList?.customApplicationId || '',
      firstMenuId: menuItem?.firstMenuId || '',
      secondMenuId: menuItem?.secondMenuId || '',
    };
    _visitRecord(data); // 记录用户打开的应用
    setState({ inputVisible: false, visible: false, searchValue: '' });
  };
  const getReplaceStr = (str) => {
    const { searchValue } = state;
    if (!searchValue) return str;
    //刘相吾说需要大小写适配
    let newStr = str
      .replaceAll(
        searchValue.toLocaleUpperCase(),
        `<span style='color:var(--base);'>${searchValue}</span>`,
      )
      .replaceAll(
        searchValue.toLocaleLowerCase(),
        `<span style='color:var(--base);'>${searchValue}</span>`,
      );
    return newStr;
  };
  // 输入框 hover展示查询内容
  const handleMouseEntert = (id, index) => {
    const { commonList } = state;
    const _menu = commonList.find((_v) => _v.customApplicationId === id);
    const contentRightNode = document.querySelectorAll(
      '.BasicLayout-ProLayout-Popover-inputSeach .contentRight .nameItem',
    );
    for (let i = 0; i < contentRightNode.length; i++) {
      if (i === index) {
        contentRightNode[i].classList.add('nameItem-action');
      } else {
        contentRightNode[i].classList.remove('nameItem-action');
      }
    }
    setState({
      seachMenuList: { ...(_menu || {}) },
    });
  };
  // 高级查询输入框
  const inputContent = () => {
    const { commonList, seachMenuList, searchValue } = state;
    return (
      <div className={style.inputContent}>
        {commonList?.length ? (
          <Fragment>
            <div className="contentRight">
              {commonList.map((_app, _index) => (
                <div
                  key={_app.customApplicationId}
                  className="nameItem"
                  onMouseEnter={() => handleMouseEntert(_app.customApplicationId, _index)}
                >
                  <div>{_app.name}</div>
                  <div>
                    {_app.children?.length || 0}个结果
                    <RightOutlined />
                  </div>
                </div>
              ))}
            </div>
            <div className="contentLeft">
              {seachMenuList?.children?.length
                ? seachMenuList.children.map((_menu) => {
                    let newStr = getReplaceStr(_menu.menuName);
                    return (
                      <div
                        key={_menu.secondMenuId}
                        dangerouslySetInnerHTML={{ __html: newStr }}
                        className="menuName"
                        onClick={() => jumpSeachPath(_menu)}
                      />
                    );
                  })
                : null}
            </div>
          </Fragment>
        ) : (
          <TRDefault type="emptysm" theme="dark" />
        )}
      </div>
    );
  };

  const handleKeyDown = (e) => {
    if (e.key.toUpperCase() === 'ENTER') {
      hanldeInput();
    }
  };
  // 高级查询 model内容
  const appContent = () => {
    const { inputVisible, searchValue, appContentLoading, appList, isRequest } = state;
    if (isRequest)
      return (
        <div className={style.loading_warp}>
          <Spin spinning={true} />
        </div>
      );
    const defaultApp = appList.filter((_v) => _v.defaultFlag); // 默认应用
    const otherApp = appList.filter((_v) => !_v.defaultFlag); // 自定义应用
    return (
      <Spin spinning={appContentLoading}>
        <div className={style.appContent}>
          {appList?.length ? (
            <Fragment>
              <div className="inputSeach">
                <Popover
                  overlayClassName="BasicLayout-ProLayout-Popover-inputSeach"
                  overlayStyle={{ padding: 0 }}
                  placement="bottom"
                  title={false}
                  trigger="click"
                  content={inputContent}
                  visible={inputVisible}
                  onVisibleChange={handleIpuntVisibleChange}
                  zIndex={10000001}
                >
                  <Input.Group compact>
                    <Input
                      value={searchValue}
                      allowClear
                      onChange={(e) => {
                        setState({ searchValue: e?.target?.value });
                      }}
                      onKeyDown={(e) => handleKeyDown(e)}
                    />
                    <Button type="primary" onClick={hanldeInput}>
                      <SearchOutlined style={{ color: '#fff' }} />
                    </Button>
                  </Input.Group>
                </Popover>
              </div>
              <div className="app">
                {defaultApp.length ? appRender(defaultApp, '应用视角切换') : null}
                {otherApp.length ? appRender(otherApp, '自定义应用') : null}
              </div>
            </Fragment>
          ) : (
            <TRDefault type="empty" theme="dark" />
          )}
        </div>
      </Spin>
    );
  };

  const appRender = (mapList, name) => {
    const { appName } = props;
    // 写死一个排序
    let list =
      name === '应用视角切换'
        ? mapList.sort((a, b) => {
            if (a.customApplicationName === '资产运营') return -1;
            if (b.customApplicationName === '资产运营') return 1;
            /* if (a.customApplicationName === '天机-发电交易') return -1;
            if (b.customApplicationName === '天机-发电交易') return 1; */
            if (a.customApplicationName === '交易辅助决策系统') return -1;
            if (b.customApplicationName === '交易辅助决策系统') return 1;
            return 0;
          })
        : mapList;
    return (
      <Fragment>
        <p className="titleTip">{name}</p>
        <div className="appList">
          {list.map((item) => (
            <div
              onClick={() => jumpApp(item)}
              key={`other-${item.customApplicationId}`}
              className={classnames(
                'appItem',
                appName === item.customApplicationName ? 'appItem-action' : null,
              )}
            >
              <div data-appitem-wrapper>
                <div className="name">{item.customApplicationName}</div>
                <div className="explain">
                  <Tooltip
                    placement="top"
                    title={() => (
                      <div style={{ whiteSpace: 'pre-line' }}>{item?.applicationExplain || ''}</div>
                    )}
                    zIndex={10000001}
                  >
                    <div className="vertical">{item?.applicationExplain || ''}</div>
                  </Tooltip>
                </div>
              </div>
            </div>
          ))}
        </div>
      </Fragment>
    );
  };

  // 高级查询弹窗model
  const handleVisibleChange = (visible) => {
    setState({ visible });
    if (visible) {
      setState({ searchValue: '' });
      // onDropdownList();
    }
  };
  return (
    <Popover
      overlayClassName="BasicLayout-ProLayout-Popover-ModelStyle"
      placement="rightTop"
      title={false}
      content={appContent()}
      visible={state.visible}
      trigger="click"
      onVisibleChange={handleVisibleChange}
      zIndex={10000000}
    >
      <RetweetOutlined className={style.icon} style={{ fontSize: '18px', color: '#fff' }} />
    </Popover>
  );
};

export default connect(({ user }) => ({
  menuObj: user?.menuObj || {},
  appName: user?.appName || '',
}))(AppBasicPopover);
